package cn.com.dhc.danlu.widget.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.widget.CursorEndEdittext;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-08-04 15:07<br/>
 *
 * <p>
 * 用以操作加减数字的Edittext
 * </p>
 */
public class NumEditext extends LinearLayout {
    private static final int MSG_COUNT_CHANGE = 0x1;

    private ImageView ivPlus;
    private ImageView ivReduce;
    private CursorEndEdittext etCount;

    // 最大可购买量 暂定为Integer.MAX_VALUE
    private int maxCount = Integer.MAX_VALUE;
    //最小起售数量
    private int mMinCount = 1;

    private OnOperationListener onOperationListener;
    private long delayTimes;
    private Handler delayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != onOperationListener) {
                onOperationListener.onCountChanged(msg.arg1);
            }
        }
    };

    public NumEditext(Context context) {
        super(context);
        init();
    }

    public NumEditext(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        setup();
    }

    public int getMaxCount() {
        return maxCount;
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    public int getMinCount() {
        return mMinCount;
    }

    public void setMinCount(int minCount) {
        mMinCount = minCount;
    }

    public long getDelayTimes() {
        return delayTimes;
    }

    public void setDelayTimes(long delayTimes) {
        this.delayTimes = delayTimes;
    }

    private void init() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.view_home_goods_count, this, true);

        ivPlus = (ImageView) rootView.findViewById(R.id.iv_plus);
        ivReduce = (ImageView) rootView.findViewById(R.id.iv_reduce);
        etCount = (CursorEndEdittext) rootView.findViewById(R.id.cee_count);
    }

    /**
     * 设置数量
     *
     * @param count
     *         数量
     */
    @SuppressLint("SetTextI18n")
    public void setDefaultCount(int count) {
        if (count >= mMinCount && count <= maxCount) {
            etCount.setText(count + "");
            etCount.setSelection(etCount.getText().toString().length());
        }
    }

    public void setOnOperationListener(OnOperationListener onOperationListener) {
        this.onOperationListener = onOperationListener;
    }

    /**
     * 获取Edittext中的值
     *
     * @return 购买数量
     */
    public String getText() {
        return etCount.getText().toString().trim();
    }

    @SuppressLint("SetTextI18n")
    public void plus() {
        String input = etCount.getText().toString();
        if (TextUtils.isEmpty(input)) {
            input = "0";
        }
        int nextCount = Integer.parseInt(input) + 1;
        if (nextCount > maxCount) {
            etCount.setText(maxCount + "");
            Toast.makeText(getContext().getApplicationContext(), "购买数量不能超过" + maxCount, Toast.LENGTH_SHORT).show();
        } else {
            etCount.setText(nextCount + "");
        }
        etCount.setSelection(etCount.getText().toString().length());
    }

    @SuppressLint("SetTextI18n")
    public void reduce() {
        String input = etCount.getText().toString();
        if (TextUtils.isEmpty(input)) {
            input = "0";
        }
        int lastCount = Integer.parseInt(input) - 1;
        if (lastCount < mMinCount) {
            etCount.setText(mMinCount + "");
            Toast.makeText(getContext().getApplicationContext(), "购买数量不能少于" + mMinCount, Toast.LENGTH_SHORT).show();
        } else {
            etCount.setText(lastCount + "");
        }
        etCount.setSelection(etCount.getText().toString().length());
    }

    private void setup() {
        ivPlus.setOnClickListener(new NoRepeatClickListener() {
            @Override
            protected void onNoRepeatClick(View v) {
                plus();
                if (null != onOperationListener) {
                    onOperationListener.onPlus(v);
                }
            }
        });

        ivReduce.setOnClickListener(new NoRepeatClickListener() {
            @Override
            protected void onNoRepeatClick(View v) {
                reduce();
                if (null != onOperationListener) {
                    onOperationListener.onReduce(v);
                }
            }
        });

        etCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                etCount.setSelection(etCount.getText().toString().length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (delayHandler.hasMessages(MSG_COUNT_CHANGE)) {
                    delayHandler.removeMessages(MSG_COUNT_CHANGE);
                }
                if (!TextUtils.isEmpty(s)) {
                    int count = Integer.valueOf(String.valueOf(s).trim());
                    Message msg = new Message();
                    msg.arg1 = count;
                    msg.what = MSG_COUNT_CHANGE;
                    delayHandler.sendMessageDelayed(msg, delayTimes);
                }
            }
        });
    }

    public EditText getEtCount() {
        return etCount;
    }

    public interface OnOperationListener {
        void onReduce(View v);

        void onPlus(View v);

        void onCountChanged(int count);
    }
}